<?php
/**
 * Created by PhpStorm.
 * User: zhao
 * Date: 2018/5/23
 * Time: 13:12
 */

namespace App\Handlers;


use App\Http\Controllers\Api\EfutureAccessTokenController;
use GuzzleHttp\Client;

class EfutureHandle extends BaseHandle
{

    public function addNewMcard($newCard)
    {
        $e_access_token = new EfutureAccessTokenController();
        $access_token = $e_access_token->accessToken()->getOriginalContent();

        if(isset($access_token['access_token']) && !empty($access_token['access_token'])){
            $request_url = 'http://122.224.86.66:8001/datahub/cmd/9005?appid=test&ACCESS_TOKEN='.$access_token['access_token'];

            //获取老卡信息
            $old_cards = $newCard->jbUserMcard()->select('cdmno')->get()->map(function($item){
                return $item->getCardTypeByCdmno($item->cdmno);
            })->collapse()->toArray();

            //上传数据
            $now_time = time();
            $post_data = [
                'timestamp'=>$now_time,

                'params'=>[
                    'p_type'=>'A',
                    'p_mkt'=>'201',
                    'p_cardtype'=>'1002',
                    'p_cardno'=>$newCard->card_no,
                    'p_createdate'=>date('YmdHis',strtotime($newCard->created_datetime)),
                    'p_carddate'=>'20991212',
                    'p_name'=>$newCard->member_optional_name,
                    'p_sex'=>$newCard->member_optional_gender,
                    'p_mobile'=>$newCard->member_optional_telephone,
                    'p_birth'=>$newCard->member_optional_birthday,
                    'p_email'=>$newCard->member_optional_emial,
                    'p_midno'=>$newCard->member_optional_identity_code,
                    'p_wechatid'=>'',
                    'p_alipayid'=>'',

                    'p_oldcardno'=>$old_cards['p_oldcardno']??'',//原解百老卡号
                    'p_hdcardno'=>$old_cards['p_hdcardno']??'',//原杭大老卡号
                    'p_lmcardno'=>$old_cards['p_lmcardno']??'',//原联名老卡号
                ],

                'sign'=>$this->getSign([$now_time,'pamtest'])
            ];

            $log_id = time().$newCard->card_no;

            //记录请求数据日志
            $this->_log(["request({$log_id}):"=>$post_data],'efuture/addNewMcard');

            $form_data = ['body'=>json_encode($post_data)];

            $client = new Client();
            $res = $client->request('POST',$request_url,$form_data);
            $result_data = json_decode($res->getBody(),true);

            //记录请求结果数据日志
            $this->_log(["response({$log_id}):"=>$result_data],'efuture/addNewMcard');

            return $result_data;

        }else{
            $this->_log(['上传注册用户会员卡失败：（access_token获取失败）'],'efuture/addNewMcard');
            return false;
        }


    }

    public function getSign(array $sign_data):string
    {
        rsort($sign_data);

        return sha1(implode($sign_data));
    }
}